package com.maserb.monitor.web.schoolStudent;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.maserb.monitor.common.*;
import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentParentEntity;
import com.maserb.monitor.enums.SexTypeEnum;
import com.maserb.monitor.model.JpushMessageModel;
import com.maserb.monitor.service.author.impl.AuthorServiceImpl;
import com.maserb.monitor.service.author_manage.UserService;
import com.maserb.monitor.service.base.IToolService;
import com.maserb.monitor.service.schoolStudent.SchoolStudentParentService;
import com.maserb.monitor.service.schoolStudent.SchoolStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping("/schoolStudentParent")
public class SchoolStudentParentController {
    @Autowired
    SchoolStudentParentService parentService;

    @Autowired
    AuthorServiceImpl authorService;

    @Autowired
    IToolService toolService;

    @Autowired
    SchoolStudentService studentService;

    @Autowired
    UserService userService;

    @Value("${monitor.parentUrl}")
    private String parentUrl;

    @RequestMapping(value = {"/", "/index"})
    public String getIndex() {
        return "school_student/index_parent";
    }

    @RequestMapping("/doListParentAdd")
    public String doListParentAdd() {
        return "school_student/index_parent_add";
    }

    @RequestMapping("/doListParent")
    @ResponseBody
    public PageResponseResult<SchoolStudentParentEntity> doListParent(PageRequestParam page, final String userName,final String realName,final String phoneNumber,final String idcard) {
        Sort.Order codeOrder = new Sort.Order(Sort.Direction.DESC, "createTime");
        List<Sort.Order> orderList = new ArrayList<Sort.Order>();
        orderList.add(codeOrder);
        Sort sort = new Sort(orderList);
        return AjaxUtils.processPage(page,sort, new Func_T1<PageRequest, Page<SchoolStudentParentEntity>>() {
            @Override
            public Page<SchoolStudentParentEntity> invoke(PageRequest var1) throws Exception {
                Page<SchoolStudentParentEntity> page = parentService.findAll(var1, userName,realName,phoneNumber,idcard);
                return page;
            }
        });
    }

    @RequestMapping("/getEditParent/{id}")
    public ModelAndView getEditParent(@PathVariable final String id) {
        ModelAndView result = new ModelAndView();
        SchoolStudentParentEntity entity = parentService.findOne(id);
        SexTypeEnum[] sexType = SexTypeEnum.values();
        result.setViewName("school_student/edit_parent");
        result.addObject("sexType",sexType);
        result.addObject("entity", entity);
        return result;
    }

    @RequestMapping("/doUpdateParent")
    @ResponseBody
    public AjaxResult<Boolean> doUpdateParent(SchoolStudentParentEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                SchoolStudentParentEntity parentEntity = parentService.findOne(entity.getId());
                /*parentEntity.setUserName(entity.getUserName());*/
                parentEntity.setIdcard(entity.getIdcard());
                parentEntity.setPhoneNumber(entity.getPhoneNumber());
                parentEntity.setRealName(entity.getRealName());
                parentEntity.setAddress(entity.getAddress());
                parentEntity.setImage(entity.getImage());
                parentEntity.setPassword(entity.getPassword());
                parentService.save(parentEntity);
                return true;
            }
        });
    }

    @RequestMapping("/getAddParent")
    public ModelAndView getAddParent() {
        ModelAndView result = new ModelAndView();
        SexTypeEnum[] sexType = SexTypeEnum.values();
        result.setViewName("school_student/add_parent");
        result.addObject("sexType",sexType);
        return result;
    }

    @RequestMapping("/doAddParent")
    @ResponseBody
    public AjaxResult<Boolean> doAddParent(SchoolStudentParentEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                SchoolStudentParentEntity parentEntity = parentService.findByUserName(entity.getUserName());
                if(null!=parentEntity && null!=parentEntity.getId()&&!"".equals(parentEntity.getId())){
                    throw new Exception("已注册该用户");
                }
                entity.setCreateTime(CreateTimeUtils.getCreateTime());
                entity.setPassword("123456");
                entity.setSalt(IdUtils.generateId());
                entity.setIsDel("0");
                parentService.save(entity);
                JpushImClientUtil.addUser(entity.getUserName(),entity.getPassword(),entity.getRealName());
                return true;
            }
        });
    }

    /**
    * @Description: 导出家长信息
    * @Param: [response, userName, name, phoneNumber, idcard]
    * @return: void
    * @Author: Mr.Wang
    * @Date: 2018/7/31
    */
    @RequestMapping(value = "/exportParentLists")
    public void exportParentLists(HttpServletResponse response, final String userName,final String realName,final String phoneNumber,final String idcard) {
        //模拟从数据库获取需要导出的数据
        List<SchoolStudentParentEntity> parentLists = parentService.findAll(userName,realName,phoneNumber,idcard);
        /*for (UserEntity entity : userLists) {
            entity.setBkfwCn(toolService.getDataTypeName("area_code", black.getBkfw()));
            entity.setFmtCreateDate(toolService.formatYYMMDDHHMMSS(black.getCreateDate()));
        }*/
        String excelName = "家长列表";
        String fileName="";
        try{
            //fileName  = new String(name.getBytes("GBK"),"ISO-8859-1")+ System.currentTimeMillis()+".xls";
            fileName  = excelName + System.currentTimeMillis()+".xls";
        }catch (Exception e){
            e.printStackTrace();
        }
        //导出操作
        ExcelExportUtils.exportExcel(parentLists, excelName, "11", SchoolStudentParentEntity.class, fileName, response);
    }

    //家长导入
    @RequestMapping("/goFileUpload")
    public ModelAndView goFileUpload() {
        ModelAndView result = new ModelAndView();
        result.addObject("parentUrl",parentUrl);
        result.setViewName("school_student/parent_import");
        return result;
    }


    @RequestMapping("/fileUpload")
    @ResponseBody
    public String fileUpload(final HttpServletRequest request, HttpServletResponse response, MultipartFile myfiles) throws IOException {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        params.setNeedVerfiy(true);
        String resultStr = "导入成功";
       /* HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        String orgId = "";
        String userId = "";
        if(null!=user){
            orgId = user.getOrgId();
            userId = user.getId();
        }*/
        try {
            ExcelImportResult result = ExcelImportUtil.importExcelMore(myfiles.getInputStream(),SchoolStudentParentEntity.class,params);
            List<SchoolStudentParentEntity> list = result.getList();
            parentService.saveByStudentId(list);
        } catch (Exception e) {
            return "导入失败！";
        }
        return resultStr;
    }



    //重置用户密码(123456)
    @RequestMapping("/doReset")
    @ResponseBody
    public AjaxResult<Boolean> doReset(@RequestParam(value = "keys[]") ArrayList<String> keys)
    {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                keys.forEach(id -> parentService.doReset(id));
                return true;
            }
        });
    }

    @RequestMapping("/doDeleteParent")
    @ResponseBody
    public AjaxResult<Boolean> doDeleteParent(@RequestParam(value = "keys[]") ArrayList<String> keys) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                parentService.deleteAllByKeys(keys);
                return true;
            }
        });
    }

    //app接口
    /**
     * 孩子列表
     * @param id
     * @return
     */
    @RequestMapping("/childrenList")
    @ResponseBody
    public AjaxResult<List<SchoolStudentEntity>> childrenList(String id) {
        return AjaxUtils.process(new Func_T<List<SchoolStudentEntity>>() {
            @Override
            public List<SchoolStudentEntity> invoke() throws Exception {
                SchoolStudentParentEntity parent = parentService.findOne(id);
                return studentService.findByParent(parent);
            }
        });
    }

    /**
     * 添加小孩
     * @param id
     * @param studentNo
     * @param studentName
     * @return
     */
    @RequestMapping("/addChild")
    @ResponseBody
    public AjaxResult<Boolean> addChild(String id, String studentNo, String studentName) {
        AjaxResult<Boolean> result = new AjaxResult<Boolean>();

        SchoolStudentParentEntity parent = parentService.findOne(id);
        SchoolStudentEntity student = studentService.findByStudentNo(studentNo);

        if(student == null) {
            result.setData(false);
            result.setMessage("该学号不存在");
        } else {
            result.setSuccess(true);
            student.setParent(parent);
            studentService.save(student);
            result.setData(true);
        }

        return result;
    }

    /**
     * 删除小孩
     * @param id
     * @param studentNo
     * @param studentName
     * @return
     */
    @RequestMapping("/removeChild")
    @ResponseBody
    public AjaxResult<Boolean> removeChild(String id, String studentNo, String studentName) {
        AjaxResult<Boolean> result = new AjaxResult<Boolean>();

        SchoolStudentParentEntity parent = parentService.findOne(id);
        SchoolStudentEntity student = studentService.findByStudentNo(studentNo);

        if(student == null) {
            result.setData(false);
            result.setMessage("该学号不存在");
        } else {
            result.setSuccess(true);
            student.setParent(null);
            studentService.save(student);
            result.setData(true);
        }

        return result;
    }

    @RequestMapping("/getMessageList/{id}")
    public ModelAndView getUpdateItem(@PathVariable final String id){
        ModelAndView result = new ModelAndView();
        result.setViewName("school_student/parent_message");
        SchoolStudentParentEntity parentEntity =parentService.findOne(id);
        String userName = parentEntity.getUserName();
        result.addObject("userName", userName);
        return result;
    }

    @RequestMapping("/getMessageListByUser/{id}")
    public ModelAndView getMessageListByUser(@PathVariable final String id){
        ModelAndView result = new ModelAndView();
        result.setViewName("school_student/parent_message");
        UserEntity userEntity =userService.findOne(id);
        String userName = userEntity.getUserName();
        result.addObject("userName", userName);
        return result;
    }

    @RequestMapping("/doMessageList")
    @ResponseBody
    public PageResponseResult<JpushMessageModel> doMessageList(PageRequestParam page, final String userName,String time) {
        List<JpushMessageModel> modelList = new ArrayList<JpushMessageModel>();
        List<JpushMessageModel> modelList2 = new ArrayList<JpushMessageModel>();
        int count = 1000;
        String begin_time = "";
        String end_time = "";
        if(StringUtils.isEmptyOrWhitespace(time)){
            end_time = CreateTimeUtils.getCreateTime();
            begin_time = CreateTimeUtils.getCreateTimeLessDays(-7);
        }else{
            end_time = CreateTimeUtils.getTimeBy(time);
            begin_time = CreateTimeUtils.getTimeLessDays(end_time,-7);
        }
        modelList  = JpushImClientUtil.getUserMessages(userName,count,begin_time,end_time);
        PageResponseResult page1 =new PageResponseResult();
        int pageNumEnd = page.getPage()*page.getLimit();
        int pageNumBegin = (page.getPage()-1)*page.getLimit();
        if(null!=modelList && modelList.size()>0){
            if(pageNumEnd>modelList.size()){
                modelList2 = modelList.subList(pageNumBegin,modelList.size());
            }else{
                modelList2 =modelList.subList(pageNumBegin,pageNumEnd);
            }
            page1.setData(modelList2);
            page1.setCount((long)modelList.size());
        }
        page1.setCode(0);
        page1.setSuccess(true);
        page1.setMsg("");
        return page1;
    }
}
